package ee.ut.maxorato_macobo.oop.mud.game;

import java.util.ArrayList;

import ee.ut.maxorato_macobo.oop.mud.items.ItemBase;

public class NpcLoader {
	static long nextLoaderIndex = 1;
	
	private NpcTemplate npcTemplate;
	private GameRoom startRoom;
	private GameCharacter currentInstance;
	private int repopTime;
	private int moveFreq;
	private long lastDeath;
	private long loaderIndex;
	private ArrayList<ItemBase> inventory;
	
	public NpcLoader(NpcTemplate newNpcTemplate, GameRoom newStartRoom, int newRepopTime, ArrayList<ItemBase> newInventory) {
		lastDeath = 0;
		
		inventory = newInventory;
		
		loaderIndex = nextLoaderIndex++;
		
		npcTemplate = newNpcTemplate;
		startRoom = newStartRoom;
		repopTime = newRepopTime;
		
		currentInstance = null;
		
		moveFreq = 20;
		
		createInstanceNow();
	}
	
	public long getIndex() {
		return loaderIndex;
	}
	
	public void createInstanceNow() {
		if(currentInstance != null) return;
		
		NpcCharacter npc = new NpcCharacter(startRoom, npcTemplate, this);
		NpcPool.registerNpc(npc);
		
		for(ItemBase item : inventory) {
			item.clone().moveToLocation(npc);
		}
		
		currentInstance = npc;
	}
	
	public void processRepopping() {
		if(currentInstance == null && lastDeath + 1000000000L * repopTime < System.nanoTime()) {
			createInstanceNow();
		}
	}
	
	public void instanceRemoved() {
		currentInstance = null;
		lastDeath = System.nanoTime();
	}
	
	public void setMoveFreq(int newMoveFreq) {
		moveFreq = newMoveFreq;
	}
	
	public int getMoveFreq() {
		return moveFreq;
	}

}
